<template>
  <el-card class="overview-card">
    <template #header>
      <div class="card-header">
        <h3>账户总览</h3>
        <div class="refresh-section">
          <span class="update-time">更新时间: {{ formatTime(lastUpdateTime) }}</span>
          <el-button :icon="Refresh" circle size="small" @click="handleRefresh" :loading="loading"></el-button>
        </div>
      </div>
    </template>
    
    <div class="account-overview">
      <div class="balance-section">
        <div class="total-balance">
          <div class="balance-label">总资产 (元)</div>
          <div class="balance-value">{{ formatAmount(balanceInfo.balance) }}</div>
        </div>
        <div class="balance-details">
          <div class="detail-item">
            <div class="detail-label">可用余额</div>
            <div class="detail-value">{{ formatAmount(calculateAvailableBalance()) }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">冻结金额</div>
            <div class="detail-value">{{ formatAmount(balanceInfo.frozenAmount) }}</div>
          </div>
        </div>
        <div class="balance-actions">
          <el-button type="primary" @click="$emit('showRechargeDialog')">充值</el-button>
          <el-button type="success" @click="$emit('showWithdrawDialog')">提现</el-button>
          <el-button type="warning" @click="$emit('showTransferDialog')">转账</el-button>
        </div>
      </div>
      <div class="balance-chart">
        <div class="chart-wrapper" ref="balanceChartRef"></div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineProps, defineEmits, watch, nextTick } from 'vue';
import { Refresh } from '@element-plus/icons-vue';
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import { 
  TitleComponent, TooltipComponent, LegendComponent, 
  GridComponent 
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册 ECharts 组件
echarts.use([
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer
]);

const props = defineProps({
  balanceInfo: {
    type: Object,
    default: () => ({ balance: 0, frozenAmount: 0 })
  },
  loading: {
    type: Boolean,
    default: false
  },
  lastUpdateTime: {
    type: Date,
    default: () => new Date()
  }
});

const emit = defineEmits(['refresh', 'showRechargeDialog', 'showWithdrawDialog', 'showTransferDialog']);

// 图表相关
const balanceChartRef = ref(null);
let balanceChart = null;

// 格式化货币金额
const formatAmount = (amount) => {
  if (amount === undefined || amount === null) return '0.00';
  return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 格式化时间
const formatTime = (dateTime) => {
  if (!dateTime) return '暂无数据';
  
  const date = new Date(dateTime);
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${hours}:${minutes}:${seconds}`;
};

// 计算可用余额
const calculateAvailableBalance = () => {
  return Math.max(0, (props.balanceInfo.balance || 0) - (props.balanceInfo.frozenAmount || 0));
};

// 初始化余额图表
const initBalanceChart = () => {
  if (!balanceChartRef.value) return;
  
  balanceChart = echarts.init(balanceChartRef.value);
  updateBalanceChart();
};

// 更新余额图表
const updateBalanceChart = () => {
  if (!balanceChart) return;
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ['可用余额', '冻结金额']
    },
    series: [
      {
        name: '账户资产',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          {
            value: calculateAvailableBalance(),
            name: '可用余额',
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            value: props.balanceInfo.frozenAmount || 0,
            name: '冻结金额',
            itemStyle: {
              color: '#E6A23C'
            }
          }
        ]
      }
    ]
  };
  
  balanceChart.setOption(option);
};

// 处理刷新
const handleRefresh = () => {
  emit('refresh');
};

// 监听余额变化，更新图表
watch(() => props.balanceInfo, () => {
  if (balanceChart) {
    updateBalanceChart();
  }
}, { deep: true });

// 初始化图表
onMounted(() => {
  nextTick(() => {
    initBalanceChart();
  });
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize);
});

// 处理窗口大小变化
const handleResize = () => {
  if (balanceChart) {
    balanceChart.resize();
  }
};

// 在组件卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  
  // 销毁图表实例
  if (balanceChart) {
    balanceChart.dispose();
    balanceChart = null;
  }
});
</script>

<style scoped>
.overview-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.refresh-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.update-time {
  font-size: 14px;
  color: #909399;
}

.account-overview {
  display: flex;
  gap: 20px;
}

.balance-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.total-balance {
  background: linear-gradient(135deg, #1e3c72, #2a5298);
  color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.balance-label {
  font-size: 14px;
  opacity: 0.8;
  margin-bottom: 5px;
}

.balance-value {
  font-size: 28px;
  font-weight: 700;
}

.balance-details {
  display: flex;
  gap: 10px;
}

.detail-item {
  flex: 1;
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 15px;
}

.detail-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.detail-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.balance-actions {
  display: flex;
  gap: 10px;
}

.balance-chart {
  flex: 1;
  min-height: 280px;
}

.chart-wrapper {
  width: 100%;
  height: 280px;
}

@media (max-width: 768px) {
  .account-overview {
    flex-direction: column;
  }
  
  .balance-details {
    flex-direction: column;
  }
}
</style>
